package com.sziit.service;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Function:文件处理相关方法
 * Notice:
 **/
@Service
public class FileService {

    /**
     *Function:从请求的request对象中获取FileItem
     *Notice:
     **/
    public List<FileItem> getFileItems(HttpServletRequest request) throws FileUploadException {
        // 获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        String path = "D:\\";
        factory.setRepository(new File(path));
        // 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        // 高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 可以上传多个文件
        List<FileItem> itemImgList = upload.parseRequest(request);
        if (itemImgList == null || itemImgList.isEmpty()) {
            System.out.println("无文件上传");
        }
        return itemImgList;
    }

    /**
     * Function: 将文件写到磁盘
     * Notice:
     **/
    public void saveFile(List<FileItem> itemImgList) {
        try {
            System.out.println("文件数量为：" + itemImgList.size());
            if (itemImgList != null) {
                // 有文件上传
                for (int i = 0; i < itemImgList.size(); i++) {
                    FileItem fileItem = itemImgList.get(i);
                    // 保存路径
                    String savePath = "D:\\";

                    //先获取文件名
                    String fileName = fileItem.getName();

                    System.out.println("文件名：" + fileName);

                    File file = new File(savePath + fileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    fileItem.write(file);
                    System.out.println("上传文件成功");
                }
            } else {
                System.out.println("无文件上传");
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            System.out.println(sw.toString());
            System.out.println("上传文件失败");
        }
    }
}
